#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Pre-patch script
	#
	#////////////////////////////////////
	# Created by MichaIng / micha@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Patches changes made to update system, critical bug fixes and changes that need to be applied before APT and patch_file to run without error
	# - Runs from dietpi-update as very first update step
	# - In case of failure, returns related pre-patch ID as exit code
	# - NB: Keep this script as simple as possible, do not load/call dietpi-globals, to allow adjusting/fixing most kinds of DietPi code first!
	#
	# Usage:
	# - ./pre-patch_file $G_DIETPI_VERSION_SUB
	#////////////////////////////////////

	# Grab input, being failsafe when applying to $G_DIETPI_VERSION_SUB
	if [[ $1 =~ ^-?[0-9]+$ ]]; then

		G_DIETPI_VERSION_SUB=$1

	else

		echo -e "\e[90m[\e[0m\e[31mFAILED\e[0m\e[90m]\e[0m Invalid input argument ($1)"
		exit 255

	fi

	# Obtain HW model
	if [[ -f '/DietPi/dietpi/.hw_model' ]] && grep -q '^G_HW_MODEL=' /DietPi/dietpi/.hw_model; then

		. /DietPi/dietpi/.hw_model

	elif [[ -f '/boot/dietpi/.hw_model' ]] && grep -q '^G_HW_MODEL=' /boot/dietpi/.hw_model; then

		. /boot/dietpi/.hw_model

	else

		# shellcheck disable=SC2015
		G_HW_MODEL=$([[ -f '/DietPi/dietpi/.hw_model' ]] && mawk 'NR==1' /DietPi/dietpi/.hw_model || mawk 'NR==1' /boot/dietpi/.hw_model)

	fi

	#///////////////////////////////////////////////////////////////////////////////
	# Main loop
	#///////////////////////////////////////////////////////////////////////////////
	#-------------------------------------------------------------------------------
	# Pre-patch 1: RAMlog 0 free space check due to issues with failing DietPi cron jobs in v6.11
	if (( $G_DIETPI_VERSION_SUB < 12 && $(df -m --output=avail /var/log | tail -1) < 2 )); then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 1 | Clearing /var/log files to free up RAMlog space (<2MB) before update will continue'
		/DietPi/dietpi/func/dietpi-logclear 1 || exit 1

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 2: https://github.com/MichaIng/DietPi/pull/2490
	if (( $G_DIETPI_VERSION_SUB < 21 )) && [[ -f '/etc/mysql/mariadb.conf.d/99-dietpi-4byte.cnf' ]] && grep -qi 'buster' /etc/os-release; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 2 | Patching /etc/mysql/mariadb.conf.d/99-dietpi-4byte.cnf for MariaDB v10.3/Buster support'
		sed -i '/innodb_large_prefix/d' /etc/mysql/mariadb.conf.d/99-dietpi-4byte.cnf || exit 2
		sed -i '/innodb_file_format/d' /etc/mysql/mariadb.conf.d/99-dietpi-4byte.cnf || exit 2

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 3: https://github.com/MichaIng/DietPi/issues/2213
	if (( $G_DIETPI_VERSION_SUB < 22 )) && GLOBAL_PW=$(openssl enc -d -a -aes-256-cbc -nosalt -pass pass:'DietPiRocks!' -in /var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin 2> /dev/null); then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 3 | Storing global DietPi-Software password with enhanced security'
		grep -qEi 'buster|bullseye' /etc/os-release && pbkdf2=('-iter' '10000') || pbkdf2=()
		openssl enc -e -a -md sha256 -aes-256-cbc "${pbkdf2[@]}" -salt -pass pass:'DietPiRocks!' -out /var/lib/dietpi/dietpi-software/.GLOBAL_PW.bin <<< "$GLOBAL_PW" || exit 3

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 5: Add new G_CHECK_URL dietpi.txt settings
	if (( $G_DIETPI_VERSION_SUB < 23 )); then

		grep -q 'CONFIG_G_CHECK_URL_TIMEOUT' /DietPi/dietpi.txt || echo 'CONFIG_G_CHECK_URL_TIMEOUT=10' >> /DietPi/dietpi.txt || exit 5
		grep -q 'CONFIG_G_CHECK_URL_ATTEMPTS' /DietPi/dietpi.txt || echo 'CONFIG_G_CHECK_URL_ATTEMPTS=2' >> /DietPi/dietpi.txt || exit 5

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 6: Move Jessie systems to "jessie-support" branch: https://github.com/MichaIng/DietPi/issues/2332
	if grep -qi 'jessie' /etc/os-release; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 6 | Migrating Jessie systems to "jessie-support" update branch'
		if grep -q '^[[:blank:]]*DEV_GITBRANCH=' /DietPi/dietpi.txt; then

			sed -i '/^[[:blank:]]*DEV_GITBRANCH=/c\DEV_GITBRANCH=jessie-support' /DietPi/dietpi.txt || exit 6

		else

			echo 'DEV_GITBRANCH=jessie-support' >> /DietPi/dietpi.txt || exit 6

		fi

		# Remove DietPi-Update working directory to allow concurrent execution.
		cd /tmp || exit 6
		[[ -d '/tmp/DietPi-Update' ]] && { rm -R /tmp/DietPi-Update || exit 6; }

		# Apply update forcefully, since user has already chosen to do so.
		/DietPi/dietpi/dietpi-update 1 || exit 6

		echo -e '\e[90m[\e[0m\e[32m  OK  \e[90m]\e[0m Everything done! Terminating the obsolete DietPi-Update parent instance...'
		kill $PPID
		exit

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 8: https://github.com/MichaIng/DietPi/issues/2795
	if (( $G_DIETPI_VERSION_SUB < 24 )) && [[ -f '/etc/apt/preferences.d/dietpi-openssl' ]]; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 8 | Patching PHP APT repo preferences to prevent possible APT upgrade issues'
		echo -e '# libssl1.1 from sury.org breaks Lighttpd install
Package: openssl libssl*\nPin: origin packages.sury.org\nPin-Priority: -1' > /etc/apt/preferences.d/dietpi-openssl || exit 8

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 9: https://github.com/MichaIng/DietPi/issues/2808
	if (( $G_DIETPI_VERSION_SUB < 25 )) && [[ -f '/etc/apt/preferences.d/dietpi-php' ]]; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 9 | Patching Buster APT repo preferences to prevent possible APT issues'
		echo -e '# Allow to install PHP7.3 dependencies and meta packages from Buster
# - Lighttpd must be pulled as well from Buster since the Stretch version does not support Buster libssl1.1 (1.1.1)
Package: php libapache2-mod-php php-* libssl* libc6* libc-* libgssapi-krb5-2 libpcre2-8-0 libk5crypto3 libkrb5-3 libkrb5support0 locales libzip4 curl libcurl4-openssl-dev lighttpd
Pin: release n=buster\nPin-Priority: 501\n
# Pin down all other Buster packages to only allow upgrades of already installed ones via: "apt upgrade"
Package: *\nPin: release n=buster\nPin-Priority: 100' > /etc/apt/preferences.d/dietpi-php || exit 9

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 10: https://github.com/MichaIng/DietPi/pull/3020
	if (( $G_DIETPI_VERSION_SUB < 26 )) && command -v xrdp &> /dev/null && grep -qi 'stretch' /etc/os-release; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 10 | Allow upgrade of XRDP from backports to resolve certain issues with current Stretch version'
		cat << _EOF_ > /etc/apt/preferences.d/dietpi-xrdp || exit 10
Package: xrdp
Pin: release n=stretch-backports
Pin-Priority: 500
_EOF_

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 11: https://github.com/MichaIng/DietPi/issues/3029
	if (( $G_DIETPI_VERSION_SUB < 26 )) && [[ -f '/etc/apt/sources.list.d/sonarr.list' ]]; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 11 | Updating Sonarr APT repository key'
		apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 0xA236C58F409091A18ACA53CBEBFF6B99D9B78493 || exit 11

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 12: https://github.com/MichaIng/DietPi/issues/3038
	if (( $G_DIETPI_VERSION_SUB < 23 )) && [[ -f '/etc/apt/sources.list.d/plex.list' ]] && grep -q 'dev2day' /etc/apt/sources.list.d/plex.list; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 12 | Removing obsolete dev2day repo for Plex Media Server, replaced by the new official APT repo'
		rm /etc/apt/sources.list.d/plex.list || exit 12

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 13/14: https://github.com/MichaIng/DietPi/issues/3131#issuecomment-536997267
	# Pre-patch 17: https://github.com/MichaIng/DietPi/issues/3031#issuecomment-540477241
	if (( $G_DIETPI_VERSION_SUB < 26 )); then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 13 | Disabling dpkg status file translations by default, which have hardly any use, but raise APT update times + disk I/O '
		echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/98-dietpi-no_translations || exit 13

		if [[ -f '/etc/apt/sources.list.d/dietpi-wireguard.list' ]]; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 14 | Switch to "bullseye" repo for WireGuard installs'
			# Raspbian
			if (( $G_HW_MODEL < 10 )) && (( ${G_RASPBIAN:=1} )); then

				echo 'deb http://raspbian.raspberrypi.org/raspbian/ bullseye main' > /etc/apt/sources.list.d/dietpi-wireguard.list || exit 14

			# non-RPi
			else

				echo 'deb https://deb.debian.org/debian/ bullseye main' > /etc/apt/sources.list.d/dietpi-wireguard.list || exit 14

			fi

		fi

		if (( $G_HW_MODEL < 10 )) && dpkg-query -s kodi &> /dev/null; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 17 | Pre-create /etc/polkit-1/localauthority/50-local.d to prevent Kodi upgrade failure'
			mkdir -p /etc/polkit-1/localauthority/50-local.d || exit 17

		fi

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 16: https://github.com/MichaIng/DietPi/pull/2571
	# Pre-patch 19: https://github.com/MichaIng/DietPi/issues/3221#issuecomment-560462951
	# Pre-patch 20: resolvconf does not depend on ifupdown anymore since v1.80 (Debian Bullseye, but we apply on all distro versions)
	if (( $G_DIETPI_VERSION_SUB < 27 )); then

		if [[ -f '/etc/apt/preferences.d/dietpi-wireguard' ]]; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 16 | Harden "bullseye" repo preferences for WireGuard installs'
			echo -e 'Package: *\nPin: release n=bullseye\nPin-Priority: -1\n
Package: wireguard wireguard-dkms wireguard-tools\nPin: release n=bullseye\nPin-Priority: 100' > /etc/apt/preferences.d/dietpi-wireguard || exit 16

		fi

		if [[ -f '/etc/kernel/postinst.d/dietpi-wireguard' ]]; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 18 | Remove WireGuard auto-rebuild skript, since DKMS is now triggered correctly'
			rm /etc/kernel/postinst.d/dietpi-wireguard || exit 18

		fi
		if [[ -f '/etc/.dietpi_hw_model_identifier' && $(</etc/.dietpi_hw_model_identifier) == 22 && -f '/etc/armbian-release' ]] && grep -q '^BOARD=zeropi$' /etc/armbian-release; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 19 | FriendlyARM ZeroPi board detected, applying new hardware ID: 59'
			echo 59 > /etc/.dietpi_hw_model_identifier

		fi
		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 20 | Mark ifupdown as manually installed to prevent its autoremoval'
		apt-mark manual ifupdown

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 21: Assure C.UTF-8 locale being available
	if (( $G_DIETPI_VERSION_SUB < 31 )) && ! locale -a | grep -qiE '^C.UTF-?8'; then

		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 21 | Compile C.UTF-8 locale as new DietPi default'
		localedef -ci C -f UTF-8 C.UTF-8
		locale -a | grep -qiE '^C.UTF-?8' || exit 21

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 22: Switch to our new Meveric's Odroid repo mirror on https://dietpi.com/meveric/
	if (( $G_DIETPI_VERSION_SUB < 33 && $G_HW_MODEL > 10 && $G_HW_MODEL < 20 )); then

		echo -e "\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 22 | Switch to our new Meveric's Odroid repo mirror on https://dietpi.com/meveric/"
		sed -Ei 's@(http://fuzon\.co\.uk|https?://oph\.mdrjr\.net)@https://dietpi.com@' /etc/apt/sources.list{,.d/*.list} || exit 22

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 23: https://github.com/MichaIng/DietPi/issues/3700
	if [[ $G_DIETPI_VERSION_SUB -lt 32 && $(uname -m) == 'x86_64' ]]; then

		# VirtualBox
		if grep -q '/dev/disk/by-id/ata-VBOX_HARDDISK_VBeda89797-79ca820f' /var/cache/debconf/config.dat; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 23 | Fixing the grub debconf drive ID'
			sed -i 's|/dev/disk/by-id/ata-VBOX_HARDDISK_VBeda89797-79ca820f|/dev/sda|' /var/cache/debconf/config.dat || exit 23

		# Native PC BIOS
		elif grep -q '/dev/disk/by-id/ata-M4-CT128M4SSD2_000000001151090024A1' /var/cache/debconf/config.dat; then

			echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 23 | Fixing the grub debconf drive ID'
			sed -i 's|/dev/disk/by-id/ata-M4-CT128M4SSD2_000000001151090024A1|/dev/sda|' /var/cache/debconf/config.dat || exit 23

		fi

	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 24: https://github.com/radxa/apt/issues/9
	if (( $G_DIETPI_VERSION_SUB < 34 && $G_HW_MODEL == 73 ))
	then
		echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 24 | Updating expired Radxa APT repository key'
		curl -sSfL https://apt.radxa.com/buster-stable/public.key | gpg --dearmor -o /etc/apt/trusted.gpg.d/dietpi-radxa.gpg --yes || exit 24
	fi
	#-------------------------------------------------------------------------------
	# Pre-patch 25: Run DietPi v7 pre-patches as part of DietPi v6 pre-patches, to assure they run before APT.
	echo -e '\e[90m[\e[0m INFO \e[90m]\e[0m Pre-patch 25 | Running DietPi v7 pre-patches'
	# - Obtain target Git repo
	if [[ -f '/DietPi/dietpi.txt' ]]
	then
		GIT_OWNER=$(sed -n '/^[[:blank:]]*DEV_GITOWNER=/{s/^[^=]*=//p;q}' /DietPi/dietpi.txt)
		GIT_BRANCH=$(sed -n '/^[[:blank:]]*DEV_GITBRANCH=/{s/^[^=]*=//p;q}' /DietPi/dietpi.txt)
	else
		GIT_OWNER=$(sed -n '/^[[:blank:]]*DEV_GITOWNER=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
		GIT_BRANCH=$(sed -n '/^[[:blank:]]*DEV_GITBRANCH=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
	fi
	[[ $GIT_OWNER ]] || GIT_OWNER='MichaIng'
	[[ $GIT_BRANCH ]] || GIT_BRANCH='master'
	curl -sSfLO "https://raw.githubusercontent.com/$GIT_OWNER/DietPi/$GIT_BRANCH/.update/pre-patches" || exit 26
	chmod +x pre-patches || exit 26
	./pre-patches || exit 26
	#-------------------------------------------------------------------------------
	# Finished
	exit 0
	#-------------------------------------------------------------------------------
}
